描述
- 浏览器要求网页中的所有资源(如 JavaScript、AJAX 请求等)只能访问同源的资源,想要访问不同源的资源,就是一个跨域问题
- 同源:协议、域名、端口都相同
实现
- 创建一个新配置文件
- 添加 @Configuration 注解,实现 WebMvcConfigurer 接口
- 重写 addCorsMappings 方法,设置允许跨域的代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有接口
.allowCredentials(true) // 是否发送 Cookie
.allowedOriginPatterns("*") // 支持域
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) // 支持方法
.allowedHeaders("*")
.exposedHeaders("*");
}
}
Last updated on